const { exec } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs-extra');

const execAsync = promisify(exec);

/**
 * Node.js版本管理器
 */
class NodeManager {
  constructor() {
    // 支持的Node.js版本配置
    this.supportedVersions = {
      'node14': {
        version: '14.19.0',
        npm: '6.14.18',
        description: '稳定版本 (推荐老项目)',
        compatible: ['node-sass', 'vue-cli', 'webpack4']
      },
      'node16': {
        version: '16.20.2',
        npm: '8.19.4',
        description: '长期支持版本',
        compatible: ['大多数项目']
      },
      'node18': {
        version: '18.18.2',
        npm: '9.8.1',
        description: '当前LTS版本',
        compatible: ['现代项目']
      },
      'node22': {
        version: '22.18.0',
        npm: '10.9.3',
        description: '最新版本',
        compatible: ['最新项目']
      }
    };
  }

  /**
   * 获取支持的版本列表
   */
  getSupportedVersions() {
    return Object.entries(this.supportedVersions).map(([key, config]) => ({
      key,
      ...config
    }));
  }

  /**
   * 检测项目推荐的Node版本
   */
  async detectRecommendedVersion(projectPath) {
    try {
      const packagePath = path.join(projectPath, 'package.json');
      
      if (!await fs.pathExists(packagePath)) {
        return 'node14'; // 默认返回稳定版本
      }

      const pkg = await fs.readJson(packagePath);
      const deps = { ...pkg.dependencies, ...pkg.devDependencies };

      // 检查engines字段
      if (pkg.engines?.node) {
        const nodeVersion = pkg.engines.node;
        if (nodeVersion.includes('>=18') || nodeVersion.includes('^18')) return 'node18';
        if (nodeVersion.includes('>=16') || nodeVersion.includes('^16')) return 'node16';
        if (nodeVersion.includes('>=14') || nodeVersion.includes('^14')) return 'node14';
      }

      // 根据依赖推断版本
      if (deps['node-sass'] || deps['node-gyp']) {
        return 'node14'; // node-sass在新版本Node中有兼容问题
      }

      if (deps['@vue/cli-service'] && deps['@vue/cli-service'].startsWith('^4')) {
        return 'node14'; // Vue CLI 4推荐Node 14
      }

      if (deps['next'] || deps['react'] || deps['@types/react']) {
        const nextVersion = deps['next'];
        if (nextVersion && nextVersion.includes('^13')) return 'node18';
        return 'node16';
      }

      if (deps['vite']) {
        return 'node16'; // Vite推荐Node 16+
      }

      // 默认推荐稳定版本
      return 'node14';

    } catch (error) {
      console.error('检测推荐版本失败:', error);
      return 'node14';
    }
  }

  /**
   * 为项目设置Node版本
   */
  async setupNodeVersion(projectPath, nodeVersion = 'node14') {
    try {
      const versionConfig = this.supportedVersions[nodeVersion];
      if (!versionConfig) {
        throw new Error(`不支持的Node版本: ${nodeVersion}`);
      }

      console.log(`🔧 设置Node.js版本: ${versionConfig.version}`);

      // 方案1: 使用nvm (如果可用)
      try {
        await this.setupWithNvm(projectPath, versionConfig);
        return { success: true, method: 'nvm', version: versionConfig };
      } catch (nvmError) {
        console.log('NVM不可用，尝试其他方案...');
      }

      // 方案2: 使用Docker容器
      try {
        await this.setupWithDocker(projectPath, versionConfig);
        return { success: true, method: 'docker', version: versionConfig };
      } catch (dockerError) {
        console.log('Docker不可用，尝试环境变量方案...');
      }

      // 方案3: 环境变量和路径设置 (兼容方案)
      await this.setupWithEnv(projectPath, versionConfig);
      return { success: true, method: 'env', version: versionConfig };

    } catch (error) {
      console.error('设置Node版本失败:', error);
      throw error;
    }
  }

  /**
   * 使用NVM设置版本
   */
  async setupWithNvm(projectPath, versionConfig) {
    // 检查nvm是否可用
    await execAsync('command -v nvm');
    
    const { version } = versionConfig;
    
    // 安装并使用指定版本
    const commands = [
      `source ~/.nvm/nvm.sh`,
      `nvm install ${version}`,
      `nvm use ${version}`,
      `echo "${version}" > .nvmrc`
    ];

    await execAsync(commands.join(' && '), { 
      cwd: projectPath,
      shell: '/bin/bash'
    });

    console.log(`✅ NVM设置完成: Node ${version}`);
  }

  /**
   * 使用Docker设置版本
   */
  async setupWithDocker(projectPath, versionConfig) {
    // 检查Docker是否可用
    await execAsync('docker --version');
    
    const { version, npm } = versionConfig;
    
    // 创建Dockerfile
    const dockerfile = `
FROM node:${version}-alpine
WORKDIR /app
RUN npm install -g npm@${npm}
COPY package*.json ./
RUN npm install
COPY . .
CMD ["npm", "run", "build"]
    `.trim();

    await fs.writeFile(path.join(projectPath, 'Dockerfile.build'), dockerfile);
    console.log(`✅ Docker配置完成: Node ${version}`);
  }

  /**
   * 使用环境变量设置 (兼容方案)
   */
  async setupWithEnv(projectPath, versionConfig) {
    const { version, npm } = versionConfig;
    
    // 创建项目专用的环境配置
    const envScript = `#!/bin/bash
# Node.js版本: ${version}
export NODE_VERSION=${version}
export NPM_VERSION=${npm}

# 设置npm配置以兼容老版本项目
npm config set legacy-peer-deps true
npm config set node-gyp-rebuild false

echo "🔧 环境设置完成: Node ${version}, NPM ${npm}"
    `.trim();

    const envPath = path.join(projectPath, '.node-env.sh');
    await fs.writeFile(envPath, envScript);
    await execAsync(`chmod +x "${envPath}"`);

    console.log(`✅ 环境变量设置完成: Node ${version}`);
  }

  /**
   * 获取构建命令 (根据Node版本调整)
   */
  getBuildCommand(nodeVersion, projectPath, buildScript) {
    const versionConfig = this.supportedVersions[nodeVersion];
    if (!versionConfig) {
      return buildScript || 'npm run build';
    }

    const commands = [];
    
    // 根据版本添加兼容性设置
    if (nodeVersion === 'node14') {
      commands.push('export NODE_OPTIONS="--max-old-space-size=4096"');
      commands.push('npm config set legacy-peer-deps true');
    }

    if (nodeVersion === 'node22') {
      commands.push('export NODE_OPTIONS="--no-deprecation"');
    }

    // 添加构建命令
    commands.push(buildScript || 'npm run build');

    return commands.join(' && ');
  }

  /**
   * 获取安装命令 (根据Node版本调整)
   */
  getInstallCommand(nodeVersion) {
    const versionConfig = this.supportedVersions[nodeVersion];
    if (!versionConfig) {
      return 'npm install';
    }

    const commands = [];

    // 根据版本添加兼容性设置
    if (nodeVersion === 'node14') {
      commands.push('npm config set legacy-peer-deps true');
      commands.push('npm config set audit false'); // 跳过安全审计加速安装
    }

    if (nodeVersion === 'node22') {
      commands.push('npm config set legacy-peer-deps false');
    }

    commands.push('npm install');

    return commands.join(' && ');
  }
}

module.exports = new NodeManager();
